import { getSystemConfig, getUserInfo, login } from '@/api/user'
import { resetRouter } from '@/router'
import { getToken, setToken, removeToken, setConfig, getConfig } from '@/utils/auth'

const state = {
  token: getToken(),
  userinfo: {},
  btnList: [],
  config: getConfig() || {
    'login_title': '欢迎登录CTS',
    'login_bg': 'upload/image/2021/04/1617893259578.jpeg',
    'system_name': 'CTS学习系统',
    'system_logo': 'upload/image/2023/06/1687263694850.jpg',
    'web_ico': 'upload/image/2023/06/1687263702799.jpg'
  }

}
const mutations = {
  setToken(state, token) {
    state.token = token
    // 同步到缓存
    setToken(token)
  },
  removeToken(state) {
    // 删除Vuex的token
    state.token = null
    removeToken()
  },
  // 存储系统配置到vuex和cookie
  setConfig(state, config) {
    setConfig(config)
    state.config = config
  },
  setUserInfo(state, userinfo) {
    state.userinfo = userinfo
  },
  setBtnList(state, btnList) {
    state.btnList = btnList
  }
}
const actions = {
  // context上下文，传入参数
  async login(context, data) {
    const res = await login(data)
    context.commit('setToken', res.token)
  },
  async getSysConfig(context) {
    const res = await getSystemConfig()
    context.commit('setConfig', res)
  },
  // 获取用户信息
  async getUserInfo(context) {
    const result = await getUserInfo()
    context.commit('setUserInfo', result.userinfo)
    context.commit('setBtnList', result.permission_btn_list)
    // 将页面权限列表返回出去，在路由守卫中使用
    return result.permission_menu_list
  },
  // 退出登录的action
  logout(context) {
    context.commit('removeToken') // 删除token
    context.commit('setUserInfo', {}) // 设置用户信息为空对象
    resetRouter() // 重置路由
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

